<?php

namespace app\admin\controller\pt;

use app\common\controller\Backend;
use app\common\library\Duty as DutyLib;
use app\admin\model\pt\Person as PersonModel;
use app\admin\model\pt\Job as JobModel;
use Exception;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 人员工作记录
 *
 * @icon fa fa-circle-o
 */
class DutyList extends Backend
{

    /**
     * DutyList模型对象
     * @var \app\admin\model\pt\DutyList
     */
    protected $model = null;

    // 劳务公司账号免除的权限
    protected $noNeedRight = ['workBatchAdd'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\pt\DutyList;

        $this->view->assign("roadList", $this->model->getIsRoadList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function work($ids)
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->where('pt_person_id', $ids)
                ->with(['job', 'depart', 'person'])
                ->order('date_id', 'desc')
                // ->order($sort, $order)
                ->paginate($limit);

            $rows = $list->items();
            foreach ($rows as &$r) {
                $r['date'] = date('m/d', strtotime($r['date_id']));
            }
            unset($r);

            $result = array("total" => $list->total(), "rows" => $rows);

            return json($result);
        }
        // 查找人
        $personId = $ids;
        $personInfo = PersonModel::get($personId);
        $this->view->assign('person', $personInfo->toArray());
        return $this->view->fetch();
    }

    public function workAdd($ids = null)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $startDate = $params['start_date'];
                $endDate = $params['end_date'];
                $departId = $params['pt_depart_id'];
                $jobId = $params['pt_job_id'];
                $personId = $params['pt_person_id'];
                if (empty($startDate) || empty($endDate) || empty($departId) || empty($jobId) || empty($personId)) {
                    $this->error('参数不完整');
                }
                $result = false;
                Db::startTrans();
                try {
                    // 批量按日期添加工作
                    $dutyLib = new DutyLib();
                    $dutyLib->batchHandleDuty($startDate, $endDate, $personId, $departId, $jobId);
                    $result = true;
                    Db::commit();
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    // echo $e->getTraceAsString();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $row = [];
        $row['pt_person_id'] = $ids;
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        // 判断日期
        $curDate = date('Ymd');
        if ($row->date_id<$curDate) {
            $this->error(__('小于当期日期不可修改'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $departId = $params['pt_depart_id'];
                $jobId = $params['pt_job_id'];
                $personId = $params['pt_person_id'];
                $date = $params['date_id'];
                if (empty($date) || empty($departId) || empty($jobId) || empty($personId)) {
                    $this->error('参数不完整');
                }

                $result = false;
                Db::startTrans();
                try {
                    $dutyLib = new DutyLib();
                    $dutyLib->handleduty($date, $personId, $departId, $jobId);
                    $result = true;
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $row->date_id = date('Y-m-d', strtotime($row->date_id));
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            // 判断日期
            $curDate = date('Ymd');
            $count = 0;
            Db::startTrans();
            try {
                $jobId = 0;
                $departId = 0;
                $dateId = 0;
                $dutyLib = new DutyLib();
                foreach ($list as $k => $v) {
                    if ($v->date_id<$curDate) {
                        throw new Exception('小于当期日期不可删除');
                    }
                    $jobId = $v->pt_job_id;
                    $departId = $v->pt_depart_id;
                    $dateId = $v->date_id;
                    if ($v->date_id == $curDate) {
                        $dutyLib->updateCurDuty($v->pt_person_id, 0, 0, null);        
                    }
                    // 处理劳务公司的删除
                    $person = PersonModel::get($v->pt_person_id);
                    $dutyLib->handleLaborLog($person, $departId, $jobId, $dateId, $v->depart_name, $v->job_name, 'del');
                    $count += $v->delete();
                }
                if ($count) {
                    // 重新计算消耗的
                    $dutyLib = new DutyLib();
                    $dutyLib->calDutyTotal($jobId, $departId, $dateId);
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
    
    // 从其他地方来添加的
    public function workBatchAdd()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                $startDate = $params['start_date'];
                $endDate = $params['end_date'];
                $jobId = $params['job_id'];
                $personIds = $params['person_ids'];
                if (empty($startDate) || empty($endDate) || empty($jobId) || empty($personIds)) {
                    $this->error('参数不完整');
                }
                $result = false;
                Db::startTrans();
                try {
                    // 根据职位查找depart
                    $jobInfo = JobModel::get($jobId);
                    if (!$jobInfo || $jobInfo->status == 'hidden') {
                        throw new Exception('岗位信息未找到');
                    }
                    $departId = $jobInfo->pt_depart_id;
                    // 批量按日期添加工作
                    $dutyLib = new DutyLib();
                    $dutyLib->batchHandlePersonsDuty($startDate, $endDate, $personIds, $departId, $jobId);
                    $result = true;
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
    
        $this->error(__('need post'));
    }

    public function clock($dutyid)
    {
        //设置过滤方法
        $duty = $this->model->get($dutyid);
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $jobInfo = JobModel::get($duty->pt_job_id);
            $clockJson = json_decode($duty->clock_json, true);
            $rows = [];
            if (!empty($clockJson)) {
                if ($jobInfo->salary_mode == 'stage') {
                  $rows[] = [
                      'id'     => 9999,
                      'clock'  => $clockJson['stage'],
                      'note'   => $clockJson['note'],
                  ];
                } else {
                    $id = 1;
                    // 先排序
                    asort($clockJson);
                    foreach ($clockJson as $c) {
                        $rows[] = [
                            'id'    => $id,
                            'clock' => date('H:i', $c),
                            'note'  => '-',
                        ];
                        $id++;
                    }
                }
            }

            $result = array("total" => count($rows), "rows" => $rows);

            return json($result);
        }
        $this->view->assign('date', date('m/d', strtotime($duty->date_id)));
        $this->view->assign('duty_id', $duty->id);
        return $this->view->fetch();
    }

    public function clockDel($dutyid)
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $this->request->post("ids");
        if ($ids) {
            $count = 1;
            Db::startTrans();
            try {
                $duty = $this->model->get($dutyid);
                $jobInfo = JobModel::get($duty->pt_job_id);
                $clockJson = json_decode($duty->clock_json, true);
                if ($jobInfo->salary_mode == 'stage') {
                    $clockJson = [];
                } else {
                    $id = 1;
                    $ids = explode(',', $ids);
                    // 先排序
                    asort($clockJson);
                    $newClockJson = [];
                    foreach ($clockJson as $c) {
                        if (in_array($id, $ids)) {
                        } else {
                            $newClockJson[] = $c;
                        }
                        $id++;
                    }
                    $clockJson = $newClockJson;
                }
                $duty->clock_json = json_encode($clockJson);
                $duty->save();
                
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    
    }

    public function clockAdd($dutyid)
    {
        $duty = $this->model->get($dutyid);
        $jobInfo = JobModel::get($duty->pt_job_id);
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $clock = $params['clock'];
                $note = empty($params['note']) ? '' : $params['note'];
                if (empty($clock)) {
                    $this->error('参数不完整');
                }
                $result = false;
                Db::startTrans();
                try {
                    // 批量按日期添加工作
                    $clockJson = json_decode($duty->clock_json, true);
                    if ($jobInfo->salary_mode == 'stage') {
                        $clockJson = [
                            'stage' => $clock,
                            'note' => $note,
                        ];
                    } else {
                        if (empty($clockJson)) {
                            $clockJson = [strtotime(date('Y-m-d', strtotime($duty->date_id)) . " " . $clock . ":00")];
                        } else {
                            $clockJson[] = strtotime(date('Y-m-d', strtotime($duty->date_id)) . " " . $clock . ":00");
                        }
                    }
                    $duty->clock_json = json_encode($clockJson);
                    $duty->save();
                    $result = true;
                    Db::commit();
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    echo $e->getTraceAsString();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $row = [];
        $row['duty_id'] = $dutyid;
        $row['salary_mode'] = $jobInfo->salary_mode;
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }
}
